#include "global.h"


const char* g_ini_file = "config/conf.ini";
ThreadPool *g_pool;
int g_udp_port;

void init_log(void) {
    /* close printf buffer */
    setbuf(stdout, NULL);
    /* initialize EasyLogger */

    ElogFileCfg cfg;
    cfg.name = "logs/log.log";
    cfg.max_size = 40 *1000 *1000;
    cfg.max_rotate = 120;

    elog_init();
    elog_file_init();
    elog_file_config(&cfg);

    /* set EasyLogger log format */
    elog_set_fmt(ELOG_LVL_ASSERT, ELOG_FMT_ALL);
    elog_set_fmt(ELOG_LVL_ERROR, ELOG_FMT_LVL | ELOG_FMT_TAG | ELOG_FMT_TIME);
    elog_set_fmt(ELOG_LVL_WARN, ELOG_FMT_LVL | ELOG_FMT_TAG | ELOG_FMT_TIME);
    elog_set_fmt(ELOG_LVL_INFO, ELOG_FMT_LVL | ELOG_FMT_TAG | ELOG_FMT_TIME);
    elog_set_fmt(ELOG_LVL_DEBUG, ELOG_FMT_ALL & ~ELOG_FMT_FUNC);
    elog_set_fmt(ELOG_LVL_VERBOSE, ELOG_FMT_ALL & ~ELOG_FMT_FUNC);
#ifdef ELOG_COLOR_ENABLE
    elog_set_text_color_enabled(true);
#endif
    /* start EasyLogger */
    elog_start();

    return;
}


void init_pool(void)
{
    // keep_alive_time, core_thread_number, max_thread_number, TaskQueue, ThreadFactory, TimeUnit
    g_pool = createThreadPool(120, 5, 12, createTaskQueue(20), createThreadFactory(), Second, DISCARD);

//    for (int i = 0; i < 100; i++) {
//        int *value = (int *) malloc(sizeof(int));
//        *value = i;
//
//        submitTask(g_pool, workFunction, value);
//
//        struct timespec sleep_time = {0, 1000 * 1000 * 100};
//        nanosleep(&sleep_time, NULL);
//    }
}

void init_config()
{
    GS32 ret = G_OK;
    char* section = "udp";
    char* key = "service_port";
    char* value = NULL;

    ret = ini_read(g_ini_file, section, key, &value);

    if (ret != G_OK)
    {
        log_a("the ini file is not corrected(%d)", ret);
        exit(-1);
    }

    if (value == NULL)
    {
        log_a("the value is NULL");
        exit(-1);
    }

    //log_i("port is %s", value);

    g_udp_port = atoi(value);

    log_i("udp service port is: %d", g_udp_port);
}

void destroy_pool()
{
//    struct timespec sleep_time = {3, 0};
//    nanosleep(&sleep_time, NULL);
    destroyThreadPool(g_pool);
}

